#!/usr/bin/python3.7
# -*- coding: utf-8 -*-
# @Time : 2019/2/27 0027
# @Email : jtyoui@qq.com
from flask import Flask, render_template, request, redirect, url_for, session, g
import config
from models import User, Question, Answer
from exts import db
from decorators import login_required
from sqlalchemy import or_

app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)


@app.route('/')
def index():
    content = {'questions': Question.query.order_by('-create_time').all()}
    return render_template('index.html', **content)


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        telephone = request.form.get('telephone')
        password = request.form.get('password')
        user = User.query.filter(User.telephone == telephone).first()
        if user and user.check_password(password):
            session['user_id'] = user.id  # 缓存
            session.permanent = True
            return redirect(url_for('index'))
        else:
            return '手机号码或者密码错误!'


@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    else:
        form = dict(request.form)
        user = User.query.filter(User.telephone == form.get('telephone')).first()
        if user:
            return '该手机号码已经被注册,请更换手机号码!'
        elif form.get('password') != form.get('re_password'):
            return '两次密码不一样,请核对以后再填写!'
        else:
            form.pop('re_password')
            user = User(**form)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('login'))


# web渲染流程:before_request --> 视图函数 --> context_processor(上下文)
@app.before_request
def before_request():
    user_id = session.get('user_id')
    if user_id:
        user = User.query.filter(User.id == user_id).first()
        g.user = user


# 登陆之后会自动检查是否登陆
@app.context_processor
def context():
    if hasattr(g, 'user'):
        return {'user': g.user}
    return {}


@app.route('/question', methods=['Get', 'POST'])
@login_required
def question():
    if request.method == 'GET':
        return render_template('question.html')
    else:
        title = request.form.get('title')
        content = request.form.get('content')
        user_id = session.get('user_id')
        q = Question(title=title, content=content, author_id=user_id)
        db.session.add(q)
        db.session.commit()
        return redirect(url_for('index'))


@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('login'))


@app.route('/detail/<question_id>')
def detail(question_id):
    questions = Question.query.filter(Question.id == question_id).first()
    return render_template('detail.html', questions=questions)


@app.route('/add_answer', methods=['POST'])
@login_required
def add_answer():
    answer_content = request.form.get('answer_content')
    question_id = request.form.get('question_id')
    user_id = session['user_id']
    answer = Answer(content=answer_content, author_id=user_id, question_id=question_id)
    db.session.add(answer)
    db.session.commit()
    return redirect(url_for('detail', question_id=question_id))


@app.route('/search')
def search():
    key = request.args.get('key')
    questions = Question.query.filter(or_(Question.title.contains(key), Question.content.contains(key)))
    return render_template('index.html', questions=questions)


if __name__ == '__main__':
    app.run()
